package com.baidu.sggc.core.common.utils;

import com.baidu.sggc.entity.UserContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class MsgSenderUtil {

    @Value("${third.mb.ak}")
    private String ak;

    @Value("${third.mb.sk}")
    private String sk;

    @Value("${third.mb.msgUrl}")
    private String baseUrl;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 构造并发送一条消息
     * @param title 消息标题
     * @param content 消息内容
     * @throws IOException 异常
     */
    public void send(String title, String content) throws IOException {
        String receiver = UserContext.getUserId(); // 当前用户
        if (receiver == null) {
            throw new IllegalArgumentException("当前用户未登录，无法发送消息");
        }

        // 构造消息体 Map（用于序列化为 JSON）
        Map<String, Object> message = new HashMap<>();
        message.put("msg_type", "bml");
        message.put("msg_secondtype", "auto-model");
        message.put("receiver", receiver);
        message.put("title", title);
        message.put("task_status", "success");

        Map<String, String> messageItem = new HashMap<>();
        messageItem.put("send_type", "internal_msg");
        messageItem.put("content", content);
        messageItem.put("link", ""); // 可为空或留默认链接

        message.put("messages", Collections.singletonList(messageItem));

        // 序列化为 JSON
        String jsonBody = OBJECT_MAPPER.writeValueAsString(message);

        // 发请求
        doPost(jsonBody);
    }

    private void doPost(String jsonBody) throws IOException {
        String requestId = UUID.randomUUID().toString();
        String timestamp = getSignTime();
        String signInput = jsonBody + sk + requestId + timestamp;

        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (Exception e) {
            throw new RuntimeException("SHA-256算法不可用", e);
        }

        byte[] hash = md.digest(signInput.getBytes(StandardCharsets.UTF_8));
        String token = String.valueOf(Hex.encodeHex(hash));

        HttpPost post = new HttpPost(baseUrl);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Access-Key", ak);
        post.setHeader("X-Bce-Request-ID", requestId);
        post.setHeader("Sign-Time", timestamp);
        post.setHeader("Token", token);
        post.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpResponse response = client.execute(post);
            int code = response.getStatusLine().getStatusCode();
            if (code < 200 || code >= 300) {
                throw new IOException("消息发送失败，状态码：" + code);
            }
        }
    }

    private String getSignTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}
